import ProForm, {
  ModalForm,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-form';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, Empty, Image, message, Popconfirm } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { formatTime } from '@/common/publicFun';
import {
  changeDoneStatus,
  changeStatus,
  doBan,
  getAllReport,
} from '@/service/reports';
import { getDetailArticle } from '@/service/article';
import { IComment, ISingleArticle } from '@/interface/Article';
import { IReport } from '@/interface/reports';

interface IProps {
  type: string;
  targetType: 'article' | 'comment' | 'reply';
  articleId: string;
  commentId?: string;
  replyId?: string;
}
export default function ReportContent() {
  const actionRef = useRef<ActionType>();
  const [detailContent, setDetailContent] = useState<string>('查找内容错误');
  const columns: ProColumns[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      hideInSearch: true,
      width: 140,
      // ellipsis: true,
      align: 'left',
    },
    {
      title: '举报描述',
      dataIndex: 'content',
      // hideInSearch: true,
      ellipsis: true,
      align: 'left',
    },
    {
      title: '举报人ID',
      dataIndex: 'userId',
      width: 120,
      // hideInSearch: true,
      align: 'left',
    },
    {
      title: '类型',
      dataIndex: 'targetType',
      width: 60,
      // hideInSearch: true,
      align: 'left',
      valueEnum: {
        article: { text: '文章' },
        comment: { text: '评论' },
        reply: { text: '回复' },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'create_Ts',
      hideInSearch: true,
      sorter: (a, b) => {
        return Number(a.create_Ts) - Number(b.create_Ts);
      },
      align: 'left',
      render: (_, _record) => (
        <span>{formatTime(_record.create_Ts, 'FULL_TIME')}</span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      editable: false,
      valueEnum: {
        1: { text: '未处理', color: 'yellow' },
        0: {
          text: '已处理',
          color: 'green',
        },
      },
    },
    {
      title: '举报原因',
      dataIndex: 'type',
      editable: false,
      valueEnum: {
        '1': { text: '含有色情内容' },
        '2': { text: '涉及第三方资金相关内容' },
        '3': { text: '含有不良政治言论' },
        '4': { text: '其他违规内容' },
      },
    },
    {
      title: '操作',
      align: 'center',
      key: 'option',
      valueType: 'option',
      render: (_, _record, index, action) => [
        <a
          key={'changeStatu' + _record.content + index}
          onClick={() => {
            handleChangeStatus({ id: _record.id });
          }}
        >
          {_record.status ? '标为已处理' : '重新激活'}
        </a>,
        <a
          key={'option' + _record.id + index}
          onClick={() => {
            handleForbiden(_record);
          }}
        >
          {_record.done ? '解封' : '封禁'}
        </a>,
        <div key={'detail' + _record.id}>
          <ModalForm
            title={'内容详情'}
            trigger={
              <a
                onClick={() => {
                  getDetail(_record);
                }}
              >
                内容详情
              </a>
            }
            submitter={{
              render: () => {
                return [];
              },
            }}
          >
            {detailContent}
          </ModalForm>
        </div>,
      ],
    },
  ];

  async function handleForbiden(params: IReport) {
    const data = await doBan(params);
    if (data.stat === 'ok') {
      const res = await changeDoneStatus({ id: params.id });
      if (res.stat === 'ok') {
        message.success('操作成功');
        actionRef.current?.reload();
        return true;
      } else {
        message.error('操作失败，' + data.msg);
      }
    } else {
      message.error('操作失败，' + data.msg);
    }
  }

  async function handleChangeStatus(params: { id: string }) {
    const data = await changeStatus(params);
    if (data.stat === 'ok') {
      message.success('操作成功');
      actionRef.current?.reload();
      return true;
    } else {
      message.error('操作失败，' + data.msg);
    }
  }

  async function getDetail(props: IProps) {
    let result: string = '查找内容错误';
    const data = await getDetailArticle({ articleId: props.articleId });
    if (data.stat === 'ok') {
      const article: ISingleArticle = data.data;
      if (props.targetType === 'article') {
        result = article.content;
      } else {
        const comments: IComment[] = article.comments;
        const findComment = comments.find(
          (item) => item.id === props.commentId,
        );
        if (findComment) {
          if (props.targetType === 'comment') {
            result = findComment?.content;
          } else {
            const replys = findComment.reply;
            const findreply = replys.find((item) => item.id === props.replyId);
            if (findreply) {
              result = findreply.content;
            } else {
              result = '回复找不到';
            }
          }
        } else {
          result = '评论找不到';
        }
      }
    }
    setDetailContent(result);
  }

  return (
    <React.Fragment>
      <ProTable
        actionRef={actionRef}
        pagination={{ pageSize: 7, current: 1, showSizeChanger: true }}
        columns={columns}
        rowKey={'id'}
        search={{ defaultCollapsed: false }}
        request={async (params, sorter, filter) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          const data = await getAllReport({
            content: params.content,
            offset: (params.pageSize || 7) * ((params.current || 1) - 1),
            limit: params.pageSize || 7,
            status:
              params.status === '0' ? 0 : params.status === '1' ? 1 : undefined,
            userId: params.userId,
            targetType: params.targetType,
            type: params.type,
            ...sorter,
          });
          return data.data;
        }}
      />
    </React.Fragment>
  );
}
